package com.sright.bcard.user.biz.manager.impl;

import com.alibaba.fastjson.JSONObject;
import com.sright.bcard.common.service.share.dto.response.CardListResponse;
import com.sright.bcard.common.service.share.dto.user.TestLoginDTO;
import com.sright.bcard.common.service.share.utils.*;
import com.sright.bcard.common.share.service.WxappService;
import com.sright.bcard.content.dal.dao.CardDAO;
import com.sright.bcard.content.dal.dao.UserDAO;
import com.sright.bcard.content.dal.dao.VersionDAO;
import com.sright.bcard.content.dal.entity.UserDO;
import com.sright.bcard.content.dal.entity.VersionDO;
import com.sright.bcard.content.dal.result.CardListDTO;
import com.sright.bcard.user.biz.manager.LoginManager;
import com.sright.bcard.user.dal.dao.MemberDAO;
import com.sright.bcard.user.dal.entity.MemberDO;
import com.sright.bcard.common.service.share.dto.user.LoginDTO;
import com.sright.bcard.user.share.request.TokenParam;
import com.sright.bcard.user.share.request.WxappLoginParam;
import lombok.SneakyThrows;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.DigestUtils;
import org.springframework.util.ResourceUtils;

import java.io.File;
import java.util.*;

@Component
public class LoginManagerImpl implements LoginManager {
    @Autowired
    private VersionDAO versionDAO;

    @Autowired
    private MemberDAO memberDAO;

    @Autowired
    private UserDAO userDAO;

    @Autowired
    private CardDAO cardDAO;

    @Autowired
    private WxappService wxappService;

    @SneakyThrows
    @Override
    public LoginDTO login(String code) {
        Map<String, Object> map = new HashMap<>();
        List<CardListDTO> personalCarIds = new LinkedList<>();
        List<CardListDTO> enterpriseCarIds = new LinkedList<>();
        LoginDTO dto = new LoginDTO();
        JSONObject jsonObject = wxappService.wechatLogin(code);
        if (jsonObject.getString("session_key") == null || jsonObject.getString("openid") == null) {
        }

        String sessionKey = jsonObject.getString("session_key");
        String openid = jsonObject.getString("openid");

        map.put("isAuthorize", 0);
        map.put("personalUserId", 0);
        map.put("enterpriseUserId", 0);
        map.put("memberId", 0);
        map.put("enterpriseId", 0);

        MemberDO memberDO = memberDAO.selectByOpenId(openid);
        if (memberDO == null) {
            memberDO = new MemberDO();
            memberDO.setSessionKey(sessionKey);
            memberDO.setOpenid(openid);
            memberDO.setCreatedAt(new Date());
            memberDO.setNickname("");
            Long memeberId = memberDAO.insertSelective(memberDO);

            dto.setIsAuthorize(0);
            dto.setEnterpriseUserId(0L);
            dto.setEnterpriseId(0L);
            dto.setPersonalUserId(0L);
            dto.setMobile("");
            dto.setMemberId(memeberId);
            map.put("memberId", memeberId);
        } else {
            memberDO.setSessionKey(sessionKey);
            memberDO.setUpdatedAt(new Date());
            memberDAO.updateSelective(memberDO);
            dto.setIsAuthorize(0);
            dto.setEnterpriseUserId(0L);
            dto.setPersonalUserId(0L);
            dto.setMobile(memberDO.getMobile().equals("") ? "" : memberDO.getMobile());
            dto.setMemberId(memberDO.getId());

            if (!memberDO.getUnionid().equals("")) {
                dto.setIsAuthorize(1);

            }
            map.put("memberId", memberDO.getId());
            List<UserDO> userDOS = userDAO.selectVerifyUser(memberDO.getId());
            if (userDOS != null) {
                for (UserDO userDO : userDOS) {
                    if (userDO.getEnterpriseId() > 0) {
                        map.put("enterpriseId", userDO.getEnterpriseId());
                        map.put("enterpriseUserId", userDO.getId());
                        dto.setEnterpriseUserId(userDO.getId());
                        dto.setEnterpriseId(userDO.getEnterpriseId());
                    } else {
                        map.put("personalUserId", userDO.getId());
                        dto.setPersonalUserId(userDO.getId());
                    }
                }
            }
        }

        //获取该用户所有企业名片ID
        if (dto.getEnterpriseUserId() > 0) {
            //先获取企业设置的名片列表
            enterpriseCarIds = cardDAO.selectIdListByEnterpriseId(dto.getEnterpriseId());
            if (CollectionUtils.isNotEmpty(enterpriseCarIds)) {
                //兼容企业未设置统一名片
                enterpriseCarIds = cardDAO.selectIdListByUserId(dto.getEnterpriseUserId());
            }
        }

        if (dto.getPersonalUserId() > 0) {
            personalCarIds = cardDAO.selectIdListByUserId(dto.getPersonalUserId());
        }

        List<CardListResponse> personalCardListResponses = new ArrayList<>();
        List<CardListResponse> enterpriseCardListResponses = new ArrayList<>();
        DataConvertUtils.convertDOList2DTOList(personalCarIds, personalCardListResponses, CardListResponse.class);
        DataConvertUtils.convertDOList2DTOList(enterpriseCarIds, enterpriseCardListResponses, CardListResponse.class);
        dto.setPersonalCardIds(personalCardListResponses);
        dto.setEnterpriseCardIds(enterpriseCardListResponses);
        Map<String, Object> result = WxappJWTUitls.createUserToken(map);
        dto.setToken((String) result.get("token"));
        dto.setExpires((Long) result.get("expires"));
        return dto;
    }

    @Override
    public Boolean setUserInfo(WxappLoginParam param, TokenParam user) throws Exception {
        MemberDO memberDO = memberDAO.selectById(user.getMemberId());
        if (memberDO == null) {
            return false;
        }

        //解密微信信息
        String result = WXBizDataCryptUtils.decrypt1(param.getEncryptedData(), memberDO.getSessionKey(), param.getIv());
        JSONObject json = JSONObject.parseObject(result);
        if (!StringUtils.isEmpty(result) && result.length() > 0) {
            if (StringUtils.isNotEmpty(json.getString("phoneNumber"))) {
                memberDO.setMobile(json.getString("phoneNumber"));
                memberDAO.updateSelective(memberDO);
                return true;
            }
            if (StringUtils.isEmpty(memberDO.getUnionid())) {
                memberDO.setCity(json.getString("city") == null ? "" : json.getString("city"));
                memberDO.setNickname(json.getString("nickName") == null ? "" : json.getString("nickName"));
                memberDO.setGender(json.getInteger("gender") == null ? 0 : json.getInteger("gender"));
                memberDO.setLanguage(json.getString("language") == null ? "" : json.getString("language"));
                memberDO.setCountry(json.getString("country") == null ? "" : json.getString("country"));
                memberDO.setProvince(json.getString("province") == null ? "" : json.getString("province"));
                memberDO.setAvatar(json.getString("avatarUrl") == null ? "" : json.getString("avatarUrl"));
                memberDO.setUnionid(json.getString("unionId") == null ? "" : json.getString("unionId"));
                if (json.getString("avatarUrl") == null) {
                    memberDO.setAvatarLocal("");
                } else {
                    String path = ResourceUtils.getURL("classpath:").getPath();
                    File upload = new File(path, "static/avatar/");
                    if (!upload.exists()) {
                        upload.mkdirs();
                    }
                    UUID uuid = UUID.randomUUID();
                    String md5Str = DigestUtils.md5DigestAsHex(uuid.toString().getBytes());
                    String fileName = md5Str + ".jpg";
                    String filePath = upload.getAbsolutePath() + File.separator + fileName;
                    FileUtils.download(json.getString("avatarUrl"), filePath);
                    AliyunUitls.uploadLocalFile("ergeng-image", "card/" + fileName, filePath);
                    new File(filePath).delete();
                    memberDO.setAvatarLocal("card/" + fileName);
                }

                memberDAO.updateSelective(memberDO);
            }

            if (StringUtils.isNotEmpty(param.getClaimId())) {
                //判断该用户是否已绑定企业名片，若已绑定，则解绑原有企业名片
                UserDO usersDO = userDAO.selectVerifyEnterpriseUser(user.getMemberId());
                if (usersDO != null) {
                    usersDO.setStatus(2);
                    usersDO.setMemberId((long) 0);
                    usersDO.setUpdatedAt(new Date());
                    userDAO.updateSelective(usersDO);
                }

                //获取现企业名片信息
                UserDO newUsersDO = userDAO.selectUnVerifyUser(Long.valueOf(param.getClaimId()));
                newUsersDO.setMemberId(user.getMemberId());
                newUsersDO.setUpdatedAt(new Date());
                newUsersDO.setVerifytime(new Date());
                newUsersDO.setStatus(1);
                userDAO.updateSelective(newUsersDO);
            }
        }
        return true;
    }

    @Override
    public LoginDTO testLogin() {
        Map<String, Object> map = new HashMap<>();
        List<CardListDTO> personalCarIds = new LinkedList<>();
        List<CardListDTO> enterpriseCarIds = new LinkedList<>();
        LoginDTO dto = new LoginDTO();
        String testMobile = "17681827613";
        Integer testAuthorize = 1;
        Long testEnterpriseUserId = 0L;
        Long testEnterpriseId = 0L;
        Long testPersonalUserId = 85L;
        Long testMemberId = 1999L;

//        String testMobile = "15101010998";
//        Integer testAuthorize = 1;
//        Long testEnterpriseUserId = 385L;
//        Long testEnterpriseId = 35L;
//        Long testPersonalUserId = 383L;
//        Long testMemberId = 450L;

        dto.setIsAuthorize(testAuthorize);
        dto.setEnterpriseUserId(testEnterpriseUserId);
        dto.setEnterpriseId(testEnterpriseId);
        dto.setPersonalUserId(testPersonalUserId);
        dto.setMobile(testMobile);
        dto.setMemberId(testMemberId);

        map.put("isAuthorize", testAuthorize);
        map.put("personalUserId", testPersonalUserId);
        map.put("enterpriseUserId", testEnterpriseUserId);
        map.put("memberId", testMemberId);
        map.put("enterpriseId", testEnterpriseId);

        //获取该用户所有企业名片ID
        if (dto.getEnterpriseUserId() > 0) {
            //先获取企业设置的名片列表
            enterpriseCarIds = cardDAO.selectIdListByEnterpriseId(dto.getEnterpriseId());
            if (CollectionUtils.isNotEmpty(enterpriseCarIds)) {
                //兼容企业未设置统一名片
                enterpriseCarIds = cardDAO.selectIdListByUserId(dto.getEnterpriseUserId());
            }
        }

        if (dto.getPersonalUserId() > 0) {
            personalCarIds = cardDAO.selectIdListByUserId(dto.getPersonalUserId());
        }

        List<CardListResponse> personalCardListResponses = new ArrayList<>();
        List<CardListResponse> enterpriseCardListResponses = new ArrayList<>();
        DataConvertUtils.convertDOList2DTOList(personalCarIds, personalCardListResponses, CardListResponse.class);
        DataConvertUtils.convertDOList2DTOList(enterpriseCarIds, enterpriseCardListResponses, CardListResponse.class);
        dto.setPersonalCardIds(personalCardListResponses);
        dto.setEnterpriseCardIds(enterpriseCardListResponses);
        Map<String, Object> result = WxappJWTUitls.createUserToken(map);
        dto.setToken((String) result.get("token"));
        dto.setExpires((Long) result.get("expires"));
        return dto;
    }

    @Override
    public TestLoginDTO showButton(String version) {
        VersionDO versionDO = versionDAO.selectById(1L);
        TestLoginDTO testLoginDTO = new TestLoginDTO();
        if (versionDO.getVersion().equals(version)) {
            testLoginDTO.setIsShow(1);
        } else {
            testLoginDTO.setIsShow(0);
        }
        return testLoginDTO;
    }
}
